package com.cynteka.cyfoman.core.mail;

import com.cynteka.cyfoman.core.Util;

import javax.mail.*;
import javax.mail.internet.MimeUtility;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * User: Sergey
 * Date: 29.07.11
 * Time: 0:56
 */
public class StoreMailHandler implements MailHandler {

    private File storeFolder;
    private String fileMask = "message-${time}.eml";
    private Logger logger = Logger.getLogger(StoreMailHandler.class.getName());

    @Override
    public void handleMessage(Message message) {
        String fileName = Util.substituteParams(fileMask, "time", System.currentTimeMillis());
        // TODO add variables
        File eml = new File(storeFolder, fileName);
        try {
//            FileOutputStream fos = new FileOutputStream(eml);
            // TODO uncomment it
//            message.writeTo(fos);
//            fos.close();

            Object content = message.getContent();
            if (content instanceof Multipart) {
                Multipart multipart = (Multipart) content;
                for (int i = 0; i < multipart.getCount(); i++) {
                    BodyPart part = multipart.getBodyPart(i);
                    String partFileName = part.getFileName();
                    if (partFileName != null) {
                        partFileName = decodeName(partFileName);
                        File f = new File(storeFolder, partFileName);
                        // TODO uncomment it
                        // saveFile(f, part);
                    }
                }
            }
        } catch (IOException e) {
            logger.log(Level.SEVERE, "Error writing message", e);
        } catch (MessagingException e) {
            logger.log(Level.SEVERE, "Error writing message", e);
        }
    }

    protected String decodeName(String name) throws UnsupportedEncodingException {
        if (name == null || name.length() == 0) {
            return "unknown";
        }
        String ret = MimeUtility.decodeText(name);
//        String ret = java.net.URLDecoder.decode( name, "UTF-8" );
//
//        // also check for a few other things in the string:
//        ret = ret.replaceAll("=\\?utf-8\\?q\\?", "");
//        ret = ret.replaceAll("\\?=", "");
//        ret = ret.replaceAll("=20", " ");

        return ret;
    }

    protected int saveFile(File saveFile, Part part) throws IOException, MessagingException {

        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(saveFile));

        byte[] buff = new byte[2048];
        InputStream is = part.getInputStream();
        int ret = 0, count = 0;
        while ((ret = is.read(buff)) > 0) {
            bos.write(buff, 0, ret);
            count += ret;
        }
        bos.close();
        is.close();
        return count;
    }


    public StoreMailHandler(File storeFolder) {
        this.storeFolder = storeFolder;
    }

}
